<?
  // compute county cente
  require_once('../db.php');
  require_once('geometry_to_array.php');
  db_connect();

  $query = 'SELECT name_CNT as name, code_CNT AS code, AsText(boundary_CNT) AS boundary FROM ldi_county_cnt ORDER BY order_CNT';
  $result = mysql_query($query) or die("ERROR PERFORMING QUERY '".$query."': ".mysql_error());
?>
<html><head><title>County Center</title></head><body>
<table border="1"><tr><th>County</th><th>Code</th><th>Center</th><th>Min</th><th>Max</th></tr>

<?
  $gminx = 0;
  $gmaxx = 0;
  $gminy = 0;
  $gmaxy = 0;
  while ($row = mysql_fetch_assoc($result)) {
    echo "<tr>";
    echo "<td>".$row["name"]."</td>";
    echo "<td>".$row["code"]."</td>";

    $b = $row["boundary"];
    $pp = geometry_to_array($b);

    $minx = 0;
    $maxx = 0;
    $miny = 0;
    $maxy = 0;
    foreach($pp[0] as $p) {
      if ($minx === 0 || $minx > $p[0])
        $minx = $p[0];
      if ($maxx === 0 || $maxx < $p[0])
        $maxx = $p[0];
      if ($miny === 0 || $miny > $p[1])
        $miny = $p[1];
      if ($maxy === 0 || $maxy < $p[1])
        $maxy = $p[1];
    }
    if ($gminx === 0 || $gminx > $minx)
      $gminx = $minx;
    if ($gmaxx === 0 || $gmaxx < $maxx)
      $gmaxx = $maxx;
    if ($gminy === 0 || $gminy > $miny)
      $gminy = $miny;
    if ($gmaxy === 0 || $gmaxy < $maxy)
      $gmaxy = $maxy;

    $cx = ($minx+$maxx)/2;
    $cy = ($miny+$maxy)/2;
    echo "<td>(" . $cy . "," . $cx . ")</td>";
    echo "<td>(" . $miny . "," . $minx . ")</td>";
    echo "<td>(" . $maxy . "," . $maxx . ")</td>";
    echo "</tr>\n";

    $query = "UPDATE ldi_county_cnt SET center_CNT=GeomFromText('POINT(".$cx." ".$cy.")') WHERE code_CNT='".$row["code"]."'";
    # $result2 = mysql_query($query) or die("ERROR PERFORMING QUERY '".$query."': ".mysql_error());
  }

  mysql_free_result($result);

  $ccx = ($gminx+$gmaxx)/2;
  $ccy = ($gminy+$gmaxy)/2;
?>


</table>
<p>Country center: (<?=$ccy?>,<?=$ccx?>)</p>
</body></html>
